package com.kugong.match;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.kugong.battle.Battle;
import com.kugong.user.User;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by lenovo on 2015/8/2.
 */
public class MatchController extends Controller {
    public void index(){
        String para = getPara();
        int page = 1;
        if (para!=null){
            page = Integer.parseInt(para);
        }
        Page<Match> matchs = Match.dao.paginate(page,20);
        setAttr("matchs",matchs);
        //查询积分前10
        List players = User.dao.qryBestPlayer();
        setAttr("players",players);
        //查询历届冠军10名
        List<Battle> battles = Battle.dao.qryChampionBattle();
        List<HashMap> champions = new ArrayList<HashMap>();
        if(battles!=null){
            for (int i = 0; i < battles.size(); i++) {
                HashMap data = new HashMap();
                Battle battle = battles.get(i);
                Battle champion = Battle.dao.qryChampion(battle.getStr("groupNo"), battle.getStr("matchId"));
                data.put("name",battle.getStr("name"));
                data.put("signName",champion.getStr("signName"));
                champions.add(data);
            }
        }
        setAttr("champions",champions);
        render("index.jsp");
    }

    public void createMatch(){
        int level = Integer.parseInt(getSessionAttr("level").toString().trim());
        if (level > 0) {
            Match match = getModel(Match.class, "Match");
            match.set("createTime", new Date());
            match.set("state", "未开始");
            match.set("ownerId", getSessionAttr("userId"));
            match.save();
            redirect("/match");
        }else{
            renderText("权限不足");
        }
    }

    public void endMatch(){
        int level = Integer.parseInt(getSessionAttr("level").toString().trim());
        if (level > 0) {
            //取出某次比赛所有人获胜轮次及总分
            //记录到point表中
            //总分汇总至user表
            //修改比赛状态
            String matchId = getPara();
            Match.dao.findById(matchId).set("state","已结束").update();
            redirect("/match");
        }else{
            renderText("权限不足");
        }
    }
}
